import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [todoList, setTodoList] = useState([
    {
      id: 1,
      todoName: '吃饭',
      isDone: true,
    },
    {
      id: 2,
      todoName: '睡觉',
      isDone: false,
    },
  ])
  console.log('app的结构体中打印的todoList', todoList)

  useEffect(() => {
    // 组件挂载,订阅
    const addToken = PubSub.subscribe('add', (topic, todoName) => {
      // 根据任务名创建任务对象
      const todo = {
        id: Date.now(),
        isDone: false,
        todoName,
      }
      console.log('在useEffect里面打印的todoList', todoList)

      // setTodoList(newTodoList)
      setTodoList((todoList) => {
        // 这个回调中的todoList一定是正确的,最新的todoList
        console.log('setTodoList回调函数中的todoList', todoList)
        const newTodoList = [...todoList]
        newTodoList.push(todo)
        // 这里返回值是什么,todoList就被改成了什么
        return newTodoList
      })
    })
    return () => {
      PubSub.unsubscribe(addToken)
    }
  }, [])

  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {todoList.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
